package cn.edu.service;

import cn.edu.common.DoctorUtils;
import cn.edu.mapper.DoctorMapper;
import cn.edu.bean.Doctor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by sang on 2017/12/28.
 */
@Service
@Transactional
public class DoctorService implements UserDetailsService {

    @Autowired
    DoctorMapper doctorMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Doctor doctor = doctorMapper.loadUserByUsername(s);
        if (doctor == null) {
            throw new UsernameNotFoundException("用户名不对");
        }
        return doctor;
    }

    public int doctorReg(String username, String password) {
        //如果用户名存在，返回错误
        if (doctorMapper.loadUserByUsername(username) != null) {
            return -1;
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(password);
        return doctorMapper.doctorReg(username, encode);
    }

    public List<Doctor> getDoctorsByKeywords(String keywords) {
        return doctorMapper.getDoctorsByKeywords(keywords);
    }

    public int updateDoctor(Doctor doctor) {
        return doctorMapper.updateDoctor(doctor);
    }

    public int updateDoctorRoles(Long doctorId, Long[] rids) {
        int i = doctorMapper.deleteRoleByDoctorId(doctorId);
        return doctorMapper.addRolesForDoctor(doctorId, rids);
    }

    public Doctor getDoctorById(Long doctorId) {
        return doctorMapper.getDoctorById(doctorId);
    }

    public int deleteDoctor(Long doctorId) {
        return doctorMapper.deleteDoctor(doctorId);
    }

    public List<Doctor> getAllDoctorExceptAdmin() {
        return doctorMapper.getAllDoctor(DoctorUtils.getCurrentDoctor().getId());
    }
    public List<Doctor> getAllDoctor() {
        return doctorMapper.getAllDoctor(null);
    }
}
